package com.sqk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqk.reggie.common.Result;
import com.sqk.reggie.pojo.Employee;
import com.sqk.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 员工管理
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        //1.将页面提交的密码进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());  //DigestUtils 是spring提供的工具类(加密)

        //2.根据页面提交的用户名查询数据库(使用mybatis-plus)
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.若没有查询到则返回登录失败
        if(emp == null){
            return Result.error("账号或密码错误！请重试！");
        }

        //4.密码对比，不一致则返回登录失败
        if (!emp.getPassword().equals(password)){
            return Result.error("账号或密码错误！请重试！");
        }

        //5.查看员工状态，是否禁用
        if (emp.getStatus() == 0){
            return Result.error("账户以禁用！");
        }

        //6.登录成功，将员工id放入session并返回结果对象
        request.getSession().setAttribute("employee",emp.getId());
        return Result.success(emp);
    }

    /**
     * 员工退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        //清除session中保存的员工id
        request.getSession().removeAttribute("employee");
        return Result.success("退出成功！");
    }

    /**
     * 添加新员工
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> addEmployee(@RequestBody Employee employee){
        //前端页面传来的信息对应表中数据不全
        //1.补充表中数据
        //a.设置员工默认密码123456，md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //添加员工
        employeeService.save(employee);
        return Result.success("添加成功!");

        /**
         * 使用mybatis-plus 自动填充功能代替下面注释功能
         */
        /*    //b.设置创建时间
        employee.setCreateTime(LocalDateTime.now());
            //c.设置修改时间
        employee.setUpdateTime(LocalDateTime.now());
            //d.设置新员工创建者,这里用的是创建者的id
        Long id = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(id);
            //e.设置修改者
        employee.setUpdateUser(id);*/
    }

    @GetMapping("/page")
    public Result<Page<Employee>> selectPage(int page, int pageSize, String name){
        log.info("page={} , pageSize={} , name={}",page,pageSize,name);

        //构造分页构造器
        Page<Employee> iPage = new Page<>(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getCreateTime);
        //执行查询
        employeeService.page(iPage,queryWrapper);

        return Result.success(iPage);
    }

    /**
     * 修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> updateEmployee(@RequestBody Employee employee){
        log.info("启用与禁用 {}",employee.toString());

        /**
         * 使用mybatis-plus 自动填充功能代替下面注释功能
         */
        //Long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setUpdateUser(empId);
        //employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return Result.success("修改成功!");


    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息。。。");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return Result.success(employee);
        }
        return Result.error("没有查到对应员工信息!");
    }

}
